<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
          title="用户中心"
      />
    </header>
    <div class="content">
      <van-form @submit="onSubmit" v-if="!flag">
        <van-field
          v-model="tel"
          name="手机号"
          label="手机号"
          placeholder="手机号"
          :rules="[{ pattern:pattern1,required: true }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ pattern:pattern2,required: true }]"
        />
        <div style="margin: 16px;">
          <van-button color="#f60" round block type="info" native-type="submit">
            登录
          </van-button>
        </div>
        <div style="margin: 16px;">
          <van-button class="button"
           round block 
           type="info" 
           native-type="submit"
           color="linear-gradient(to right, #4bb0ff, #6149f6)"
           to="/register"
           >
            注册
          </van-button>
        </div>
      </van-form>
      
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { NavBar,Form,Field,Button,Toast } from 'vant'
import { login } from '@/api'

Vue.use(Form)
Vue.use(NavBar)
Vue.use(Field)
Vue.use(Button )
Vue.use(Toast )
export default {
  data () {
    return {
      tel:'15196345101',
      password:'123456',
      pattern1: /^1[3456789]\d{9}$/,
      pattern2: /\d{6}/,
      flag:localStorage.getItem('loginState') === 'ok'
    }
  },
  //自定义函数
  methods: {
    //登录按钮
    onSubmit(){
      console.log('提交')
      login ({
        tel: this.tel,
        password: this.password
      }).then(res => {
        console.log(res.data)
        //解构出code
        const { code } = res.data
        switch(code){
          case '10888':
            this.flag = false
            Toast("登陆成功")
            //存储用户信息到本地
            localStorage.setItem('nickname',res.data.data.nickname)
            localStorage.setItem('token',res.data.data.token)
            localStorage.setItem('userid',res.data.data.userid)
            //再存储一个登录状态
            localStorage.setItem('loginState','ok')
            break
          case "10808":
            Toast("该用户未注册")
            break
          case "10400":
            Toast("请完善表单信息")
            break
          default:
            break
        }
      })
    }
  },
  //vue加载后的钩子函数，用来请求数据
  mounted() {
    
  },
}
</script>
<style lang='scss' scoped>
.van-form{
  margin-top: 5%;
}
.button{
  margin-top: 10px;
}
</style>
